package com.dream.myqiyi.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.dream.myqiyi.Global;
import com.dream.myqiyi.dao.NotebookModel;
import com.dream.myqiyi.db.MainDBHelper;

public class NotebookService {
	
	private List<String>			selectedNotebooks;
	private List<NotebookModel>		notebookIndex;
	private List<NotebookModel>		archiveNotebookIndex;
	private List<String>			localNotebookIndex;
	private Map<String, NotebookModel> allNotebook;
	private boolean					isDirty;
	private NotebookModel			currNotebook;
	
	private NotebookManager			notebookMgr;
	
	public NotebookService() {
		allNotebook = new HashMap<String, NotebookModel>();
		notebookMgr = (NotebookManager)ApplicationContext.getSingleton().getBean("NotebookManager");
		isDirty = true;
	}
	
	public boolean init() {
		if (isDirty) {
			updateAllNotebook();
		}
		for (Map.Entry<String, NotebookModel> entry : allNotebook.entrySet()) {
			NotebookModel note = entry.getValue();
			if (note.isDefaultNotebook()) {
				currNotebook = note;
				return true;
			}
		}
		NotebookModel nb = new NotebookModel();
		nb.setName(Global.username + "的笔记本");
		nb.setGuid(Global.getGuid());
		setCurrNotebook(nb);
		if (currNotebook == null) {
			currNotebook = this.addNotebook(Global.username + "的笔记本");
		}
		return true;
	}
	
	public NotebookModel getCurrNotebook() {
		return currNotebook;
	}
	
	public void setCurrNotebook(NotebookModel nb) {
		if (currNotebook != null) {
			if (nb.getGuid() == currNotebook.getGuid()) {
				return ;
			}
			currNotebook.setDefaultNotebook(false);
			this.updateNotebook(currNotebook);
		}
		currNotebook = nb;
		currNotebook.setDefaultNotebook(true);
		this.updateNotebook(currNotebook);
		if (!allNotebook.containsKey(currNotebook.getGuid())) {
			allNotebook.put(currNotebook.getGuid(), currNotebook);
		}
			
	}
	
	public NotebookModel getNotebook(String guid) {
		if (isDirty) {
			updateAllNotebook();
		}
		return allNotebook.get(guid);
	}
	
	public NotebookModel getNotebookByName(String name) {
		if (isDirty) {
			updateAllNotebook();
		}
		
		for (Map.Entry<String, NotebookModel> entry : allNotebook.entrySet()) {
			NotebookModel note = entry.getValue();
			if (name == note.getName()) {
				return note;
			}
		}
		return null;
	}
	
	public void updateAllNotebook() {
		isDirty = false;
		allNotebook.clear();
		List<NotebookModel> nbList = notebookMgr.getAll();
		
		for (NotebookModel nb : nbList) {
			allNotebook.put(nb.getGuid(), nb);
		}
	}
	
	public ArrayList<NotebookModel> getAllNotebook() {
		if (isDirty) {
			updateAllNotebook();
		}
		return new ArrayList<NotebookModel>(allNotebook.values());

	}
	
	public NotebookModel addNotebook(String name) {
		if (isDirty) {
			updateAllNotebook();
		}
		
		for (Map.Entry<String, NotebookModel> entry : allNotebook.entrySet()) {
			NotebookModel note = entry.getValue();
			if (name == note.getName()) {
				return note;
			}
		}
		
		NotebookManager mgr = (NotebookManager)ApplicationContext.getSingleton().getBean("NotebookManager");
		if (mgr != null)
		{
			NotebookModel nb = new NotebookModel();
			nb.setName(name);
			nb.setGuid(Global.getGuid());
			nb = mgr.save(nb);
			
			allNotebook.put(nb.getGuid(), nb);
			return nb;
		}
		return null;
	}
		
	public void addNotebook(NotebookModel b) {
		
		try {
			MainDBHelper.getSingleton().getNotebookDao().create(b);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		notebookIndex.add(b);
	}
	
	public NotebookModel findNotebook(String guid) {
		return null;
	}

	// Delete a notebook
	public void deleteNotebook(String guid) {
		notebookMgr.remove(guid);
		allNotebook.remove(guid);
	}
	
	// update a notebook
	public void updateNotebook(NotebookModel notebook) {
		notebookMgr.save(notebook);
	}
	
	public int getAllNotebookCount() {
		if (isDirty) {
			updateAllNotebook();
		}

		return allNotebook.size();
	}
	

	//***************************************************************
	//***************************************************************
	//* selected notebooks
	//***************************************************************
	//***************************************************************
 	// Return the selected notebook(s)
	public List<String> getSelectedNotebooks() {
		return selectedNotebooks;
	}
	// Set the current selected notebook(s)
	public void setSelectedNotebooks(List <String> s) {
		if (s == null) 
			s = new ArrayList<String>();
		selectedNotebooks = s;
	}

	private void setNotebookIndex(List<NotebookModel> t) {
		notebookIndex = t;
	}
	// Retrieve the Notebook index
	public List<NotebookModel> getNotebookIndex() {
		return notebookIndex;
	}
	private void setArchiveNotebookIndex(List<NotebookModel> t) {
		archiveNotebookIndex = t;
	}
	public List<NotebookModel> getArchiveNotebookIndex() {
		return archiveNotebookIndex;
	}
	public List<String> getLocalNotebooks() {
		return localNotebookIndex;
	}

	
	// Rename a stack
	public void renameStack(String oldName, String newName) {
		for (int i=0; i<getNotebookIndex().size(); i++) {
			if (getNotebookIndex().get(i).getStack() != null && 
					getNotebookIndex().get(i).getStack().equalsIgnoreCase(oldName)) {
				getNotebookIndex().get(i).setStack(newName);
			}
		}	
	}
	// Update a notebook sequence number
	public void updateNotebookSequence(String guid, int sequence) {
 	   Log.i("[MyNeverNote]", "Entering ListManager.updateNotebookSequence");

		for (int i=0; i<notebookIndex.size(); i++) {
			if (notebookIndex.get(i).getGuid().equals(guid)) {
				notebookIndex.get(i).setSequence(sequence);
				updateNotebook(notebookIndex.get(i));
				
				i=notebookIndex.size()+1;				
			}
		}
		Log.i("[MyNeverNote]", "Leaving ListManager.updateNotebookSequence");

	}
	// Update a notebook Guid number
	public void updateNotebookGuid(String oldGuid, String newGuid) {
		Log.i("[MyNeverNote]", "Entering ListManager.updateNotebookGuid");
		
		for (int i=0; i<notebookIndex.size(); i++) {
			if (notebookIndex.get(i).getGuid().equals(oldGuid)) {
				notebookIndex.get(i).setGuid(newGuid);
				updateNotebook(notebookIndex.get(i));
				
				i=notebookIndex.size()+1;
			}
		}
		Log.i("[MyNeverNote]", "Leaving ListManager.updateNotebookGuid");
	}
	// Update a notebook Guid number
	public void updateNotebookStack(String oldGuid, String stack) {
		Log.i("[MyNeverNote]", "Entering ListManager.updateNotebookGuid");

		for (int i=0; i<notebookIndex.size(); i++) {
			if (notebookIndex.get(i).getGuid().equals(oldGuid)) {
				notebookIndex.get(i).setStack(stack);
				updateNotebook(notebookIndex.get(i));
				
				i=notebookIndex.size()+1;
			}
		}
		Log.i("[MyNeverNote]", "Leaving ListManager.updateNotebookGuid");

	}

	// For a notebook guid, return the name
	public String getNotebookNameByGuid(String guid) {
		if (notebookIndex == null)
			return null;
		for (int i=0; i<notebookIndex.size(); i++) {
			String s = notebookIndex.get(i).getGuid();
			if (s.equals(guid)) { 
				return notebookIndex.get(i).getName();
			}
		}
		return "";
	}
	
	//////////////////////////////////////////////
	public JSONObject toJsonData(NotebookModel nb) {
		try {
			JSONObject ret = new JSONObject();
			ret.put("id", nb.getGuid());
			ret.put("name", nb.getName());
			ret.put("owner", Global.DEFAULT_USERNAME);
			return ret;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	public NotebookModel fromJsonData(JSONObject nbParam) {
		NotebookModel nb = new NotebookModel();
		try {
			// 删除notebook
			if (nbParam.getLong("deletedTime") != 0) {
				deleteNotebook(nbParam.getString("id"));
				return null;
			}
			
			nb.setGuid(nbParam.getString("id"));
			nb.setName(nbParam.getString("name"));
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		return nb;
	}
}
